#ifndef LOADER_HPP
#define LOADER_HPP

#include <iostream>
#include <QtOpenGL>
#include <QFile>
#include <QTextStream>
#include <QVarLengthArray>
#include <QVector>
#include <QFileInfo>
#include "model3d.hpp"

static void loadModel(const std::string &filePath, Model3D &model)
{
    /*Openning file code*/
    QFile file(QString(filePath.c_str()));

    if(!file.open(QIODevice::ReadOnly))
    {
        std::cout << "Error : Can't open file" << std::endl;
        file.close();
        return;
    }

    /*Take file name*/
    model.setName(QFileInfo(QString(filePath.c_str())).fileName().toStdString());

    float boundsMin[3] = {1e9f, 1e9f, 1e9f};
    float boundsMax[3] = {-1e9f, -1e9f, -1e9f};

    QTextStream in(&file);
    while(!in.atEnd())
    {
        QString line = in.readLine();
        if(line.isEmpty() || line[0] == '#')
            continue;

        QTextStream ts(&line);
        QString id;

        ts >> id;

        if( id == "v")
        {
             for(int i = 0; i < 3; i++)
             {
                 ts >> id;

                 boundsMin[i] = qMin(boundsMin[i], id.toFloat());
                 boundsMax[i] = qMax(boundsMax[i], id.toFloat());

                 model.addVertex(id.toFloat());
             }
        }
        else if( id == "f")
        {
            QVarLengthArray<unsigned int, 4> face;

            while(!ts.atEnd())
            {
                QString vertex;
                ts >> vertex;
                const int vertexIndex = vertex.split('/').value(0).toInt();


                if (vertexIndex)
                    face.append(vertexIndex > 0 ? vertexIndex - 1 : model.getVertexArraySize() + vertexIndex);
            }

            for (int i = 0; i < 3; ++i)
                model.addFace(face[i]);

            if (face.size() == 4)
                for (int i = 0; i < 3; ++i)
                    model.addFace(face[(i + 2) % 4]);
        }
    }

    model.setBoundingBox(boundsMin, boundsMax);
    model.init();

    file.close();
};

#endif // LOADER_HPP
